package com.aweqy.librarymanager.controller;

import com.aweqy.librarymanager.entity.SysUser;
import com.aweqy.librarymanager.service.SysUserService;
import com.aweqy.librarymanager.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        SysUser user = sysUserService.getByUsername(username);
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (user == null || !user.getPassword().equals(md5Password) || user.getStatus() != 1) {
            return ResponseEntity.status(401).body("用户名或密码错误");
        }
        String token = jwtUtil.generateToken(username);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/info")
    public ResponseEntity<?> info(Authentication authentication) {
        SysUser user = (SysUser) authentication.getPrincipal();
        return ResponseEntity.ok(user);
    }
} 